<template>
    <el-dialog :model-value="modelValue" title="分配角色" width="30%" @close="handleClose">
        <el-form ref="formRef" :model="form" label-width="100px">
            <el-checkbox-group v-model="form.checkedRoles">
                <el-checkbox v-for="role in form.roleList" :key="role.id" :label="role.id"
                    name="checkedRoles">{{ role.name }}</el-checkbox>
            </el-checkbox-group>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="handleConfirm">确认</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>
    
<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil, { getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus';

const props = defineProps({
    id: {
        type: Number,
        default: -1,
        required: true
    },
    modelValue: {
        type: Boolean,
        default: false,
        required: true
    },
    roleList: {
        type: Array,
        default: [],
        required: true
    }
});

const form = ref({
    id: -1,
    roleList: [],
    checkedRoles: []
})

const initFormData = async (id) => {
    const result = await requestUtil.get('/sys/role/listAll');
    let data = result.data;
    form.value.roleList = data.result;
    form.value.id = id;
}

watch(() => props.modelValue , () => {
    let id = props.id;
    if (id != -1) {
        form.value.checkedRoles = [];
        props.roleList.forEach(item => form.value.checkedRoles.push(item.id));
        console.log('check:', props.roleList);
        
        initFormData(id);
    }
})

// 关闭弹窗
const emits = defineEmits(['update:modelValue', 'initUserList']);

const handleClose = ()=>{
    emits('update:modelValue', false);
}

// 提交表单
const formRef = ref(null);
const handleConfirm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            const result = await requestUtil.post('/sys/user/grantRoles/' + form.value.id, form.value.checkedRoles);
            let data = result.data;
            if (data.code == 2000) {
                ElMessage.success("执行成功！")
                emits("initUserList")
                handleClose();
            } else {
                ElMessage.error(data.msg);
            }
        }

    })
}


</script>


<style lang="scss" scoped>

</style>